package com.sinodata.bsm.cicp.collector.common;

import java.io.FileWriter;
import java.net.SocketException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.sinodata.bsm.cicp.collector.Collector;
import com.sinodata.bsm.cicp.exception.CollectorException;
import com.sinodata.bsm.common.constants.DataTypeConstants;
import com.sinodata.bsm.common.vo.ResPropertyValue;

/**
 * 
 * <p>
 * Description: Http仿真采集器
 * </p>
 *
 * @author liulibo
 * @version 1.0

 * <p>
 * History: 
 *
 * Date                     Author         Version     Description
 * ---------------------------------------------------------------------------------
 * 2012-11-12 14:34:44      liulibo        1.0         To create
 * </p>
 *
 * @since 
 * @see
 */
public class HttpRptServer extends Collector {

    /**
     * 记录日志
     */
    private static final Logger logger = Logger.getLogger(HttpRptServer.class);

    @Override
    public List<ResPropertyValue> collect(String ip) throws CollectorException {
        String proxyIp = this.getParamMap().get("HTTP IP");//代理服务器的IP
        String sProxyPort = this.getParamMap().get("HTTP Port");//代理服务器的端口
        int proxyPort = 0;
        if (sProxyPort != null && sProxyPort.length() > 0) {
            proxyPort = Integer.parseInt(sProxyPort);
        }
        String appUrl = this.getParamMap().get("HTTP Application URL");//Http连接的应用URL
        String[] propMetas = getPropMeta();
        ResPropertyValue propertyValueX = new ResPropertyValue();
        ResPropertyValue.PropValue[] propValues = new ResPropertyValue.PropValue[propMetas.length];
        List<ResPropertyValue> values = new ArrayList<ResPropertyValue>();
        HttpMethod method = null;
        String matchContent = this.getParamMap().get("match_content");
        String[] matchContentArray = { "" };
        if (matchContent != null) {
            matchContentArray = matchContent.trim().split("[,]");
        }
        try {
            HttpClient client = getHttpClient(proxyIp, proxyPort);
            client.getHttpConnectionManager().getParams().setConnectionTimeout(60000);
            method = getGetMethod(appUrl);
            long time = testHttpConnect(client, method);

            String responseBody = method.getResponseBodyAsString();
            if (time == -1) {
                propValues[0] = ResPropertyValue.createPropValue("2000", propMetas[0]);
                propValues[1] = ResPropertyValue.createPropValue(DataTypeConstants.BOOLEAN_VALUE_FALSE, propMetas[1]);
            } else {
                propValues[0] = ResPropertyValue.createPropValue("" + time, propMetas[0]);
                propValues[1] = ResPropertyValue.createPropValue(DataTypeConstants.BOOLEAN_VALUE_TRUE, propMetas[1]);
            }
            boolean isMatch = false;
            if (responseBody != null) {
                for (String e : matchContentArray) {
                    if (e.equals(""))
                        continue;
                    if (StringUtils.containsIgnoreCase(responseBody, e)) {
                        isMatch = true;
                    } else {
                        isMatch = false;
                        break;
                    }
                }
            }
            if (isMatch) {
                propValues[2] = ResPropertyValue.createPropValue(DataTypeConstants.BOOLEAN_VALUE_TRUE, propMetas[2]);
            } else {
                propValues[2] = ResPropertyValue.createPropValue(DataTypeConstants.BOOLEAN_VALUE_FALSE, propMetas[2]);
            }
            propertyValueX.setValues(propValues);
            values.add(propertyValueX);
            return values;
        } catch (Exception e) {

            return values;
        } finally {
            if (method != null) {
                method.releaseConnection();
            }
        }
    }

    /**
     * 测试HTTP连接
     * 
     * @param client
     * @param method
     * @return
     * @throws Exception
     */
    private long testHttpConnect(HttpClient client, HttpMethod method) throws Exception {
        long time = System.currentTimeMillis();
        try {
            client.executeMethod(method);
        } catch (SocketException e) {
            logger.error("HttpRptServer test http connect SocketException", e);
            return -1;
        } finally {
        }
        int statuscode = method.getStatusCode();
        if (statuscode == 200 || statuscode == 202) {
            return System.currentTimeMillis() - time;
        } else {
            logger.info(statuscode);
            SimpleDateFormat sdf = new SimpleDateFormat("", Locale.SIMPLIFIED_CHINESE);
            sdf.applyPattern("yyyy年MM月dd日_HH时mm分ss秒");
            String timeStr = sdf.format(new Date());
            FileWriter writer = null;
            try {
                writer = new FileWriter("./HttpConnect.txt", true);
                writer.append(timeStr + " " + "获取的返回码" + " " + statuscode + "\n");
                writer.flush();
            } catch (RuntimeException e) {
                logger.error(e);
                return -1;
            } finally {
                writer.close();
            }
            return -1;
        }
    }

    /**
     * 使用get方式提交数据
     * 
     * @return
     */
    private HttpMethod getGetMethod(String s) {
        return new GetMethod(s);
    }

    /**
     * 获得HttpClient,ip为代理IP port为代理端口
     * 
     * @param ip
     * @param port
     * @return
     */
    private HttpClient getHttpClient(String ip, int port) {
        HttpClient client = new HttpClient();
        if (ip != null && ip.matches("(25[0-5]|2[0-4]\\d|1\\d{2}|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d{2}|[1-9]?\\d)){3}")) {
            client.getHostConfiguration().setProxy(ip, port);
            logger.info("使用代理:" + ip);
        }
        return client;
    }

    /*
     * (non-Javadoc)
     * @see com.sinodata.bsm.cicp.collector.Collector#getParamMeta()
     * HTTP IP               Http代理的ip
     * HTTP Port             Http代理端口
     * HTTP Application URL  Http连接的应用URL
     * match_content         匹配内容
     */
    @Override
    public String[] getParamMeta() {
        return new String[] { "HTTP IP", "HTTP Port", "HTTP Application URL", "match_content" };
    }

    /*
     * (non-Javadoc)
     * @see com.sinodata.bsm.cicp.collector.Collector#getPropMeta()
     * HTTP_Connection_Response_Time   连接耗时
     * Whether_Connect                 是否连接系统
     * is_match                        是否匹配
     */
    @Override
    public String[] getPropMeta() {
        return new String[] { "HTTP_Connection_Response_Time", "Whether_Connect", "is_match" };
    }

}
